package main

import (
	"./robot"
	"flag"
	"log"
	"runtime"
	"bufio"
	"os"
	"strings"
	"strconv"
)

var q chan int
var ch chan int
var robotid int

func main() {
    runtime.GOMAXPROCS(1)

	q = make(chan int, 1)

	sLoginServerAddr := "192.168.0.16:3000"
	iZoneId := 1
	iRobotNum := 1
	ch = make(chan int, 1)

    flag.StringVar(&sLoginServerAddr, "addr", "192.168.0.16:3000", "Use --addr <ip:port>")
    flag.IntVar(&iZoneId, "zoneid", 1, "Use --zoneid <zone>")
    flag.IntVar(&iRobotNum, "num", 1, "Use --num <num>")
    flag.Parse()

	robot.Init();

	for i := 0; i < iRobotNum; i++ {
		robotid++
		go robot.CreateRobot(robotid, ch)
	}

	// 开启命令行
	go terminal()

	// 等待所有机器人结束
    for {
        select {
		case id := <-ch:
			if (robot.DeleteRobot(id)) {
				return
			}
		case <-q:
			robot.ExitRobot()
        }
    }

	robot.Destroy()
}

func terminal() {

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		input := strings.Trim(scanner.Text(), "\r\n ")
		cmds := strings.Split(input, " ")
		if len(cmds) == 0 {
			continue
		}

		if strings.Compare("q", cmds[0]) == 0 {
				q <- 1
		} else if (strings.Compare("a", cmds[0])) == 0 {
				num := 1
				if len(cmds) > 1 {
					var err error
					if num,err = strconv.Atoi(cmds[1]); err != nil {
						continue
					}
				}
				for i:=0; i<num; i++ {
					robotid++
					go robot.CreateRobot(robotid, ch)
				}
		} else if (strings.Compare("d", cmds[0])) == 0 {
			if len(cmds) < 2 {
				continue;
			}
			/*var id int
			var err error
			if id,err = strconv.Atoi(cmds[1]); err != nil {
				continue;
			}
			*/
		} else {
			log.Println("invalid cmd:", cmds)
		}
	}
}
